import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import fs from 'fs';
import path from 'path';

export async function GET() {
  try {
    // 先尝试从数据库获取配置
    const config = await db.get<any>(`
      SELECT * FROM site_config ORDER BY id LIMIT 1
    `);
    
    if (config) {
      return NextResponse.json({
        success: true,
        data: {
          title: config.title,
          subtitle: config.subtitle,
          description: config.description,
          logo: config.logo,
          favicon: config.favicon,
          contact: JSON.parse(config.contact_info || '{}'),
          theme: JSON.parse(config.theme || '{}'),
          seo: JSON.parse(config.seo || '{}'),
          navigation: JSON.parse(config.navigation || '[]'),
          footer: JSON.parse(config.footer || '{}'),
          analytics: JSON.parse(config.analytics || '{}'),
          carousel: JSON.parse(config.carousel_settings || '{"interval": 4000, "transition": "smooth", "autoPlay": true, "pauseOnHover": true}')
        }
      });
    }
    
    // 如果数据库没有，则从 JSON 文件获取
    const configPath = path.join(process.cwd(), 'config', 'site.json');
    if (fs.existsSync(configPath)) {
      const fileConfig = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
      return NextResponse.json({
        success: true,
        data: fileConfig
      });
    }
    
    // 返回默认配置
    return NextResponse.json({
      success: true,
      data: {
        title: '机器人创新实验室',
        description: '致力于机器人技术研发与创新，培养优秀的机器人工程师',
        contactInfo: {
          address: '北京市海淀区中关村大街1号',
          phone: '010-12345678',
          email: 'contact@roboticslab.com'
        }
      }
    });
  } catch (error) {
    console.error('Error fetching config:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to fetch config'
    }, { status: 500 });
  }
}

export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证必填字段
    if (!body.title || !body.description) {
      return NextResponse.json({
        success: false,
        error: 'Title and description are required'
      }, { status: 400 });
    }

    // 准备要保存的数据
    const configData = {
      title: body.title,
      subtitle: body.subtitle || '',
      description: body.description,
      logo: body.logo || null,
      favicon: body.favicon || null,
      theme: JSON.stringify(body.theme || {}),
      contact_info: JSON.stringify(body.contact || {}),
      seo: JSON.stringify(body.seo || {}),
      carousel_settings: JSON.stringify(body.carousel || {}),
      updated_at: new Date().toISOString()
    };

    // 检查是否已存在配置
    const existingConfig = await db.get(`
      SELECT id FROM site_config ORDER BY id LIMIT 1
    `);

    if (existingConfig) {
      // 更新现有配置
      await db.run(`
        UPDATE site_config SET 
          title = ?,
          subtitle = ?,
          description = ?,
          logo = ?,
          favicon = ?,
          theme = ?,
          contact_info = ?,
          seo = ?,
          carousel_settings = ?,
          updated_at = ?
        WHERE id = ?
      `, [
        configData.title,
        configData.subtitle,
        configData.description,
        configData.logo,
        configData.favicon,
        configData.theme,
        configData.contact_info,
        configData.seo,
        configData.carousel_settings,
        configData.updated_at,
        existingConfig.id
      ]);
    } else {
      // 创建新配置
      await db.run(`
        INSERT INTO site_config (
          title, subtitle, description, logo, favicon,
          theme, contact_info, seo, carousel_settings, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `, [
        configData.title,
        configData.subtitle,
        configData.description,
        configData.logo,
        configData.favicon,
        configData.theme,
        configData.contact_info,
        configData.seo,
        configData.carousel_settings,
        configData.updated_at
      ]);
    }

    return NextResponse.json({
      success: true,
      message: 'Configuration saved successfully'
    });

  } catch (error) {
    console.error('Error saving config:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to save configuration'
    }, { status: 500 });
  }
}